package tk.mybatis.springboot.share.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import tk.mybatis.springboot.wexin.bean.TWechatMediaNews;
import tk.mybatis.springboot.wexin.bean.WeChatMessageBean;
import tk.mybatis.springboot.wexin.enums.WechatMessageTypeEnum;

/**
 * 微信媒体类素材工具包
 * @title:WechatMediaUtil
 * @form:Mr_xing
 * @author Administrator
 * @date 2017年3月16日 下午2:26:28
 */
public class WechatMediaUtil {

	private static final Logger logger = Logger.getLogger(WechatMediaUtil.class);

	/** 永久素材上传地址 */
	public static final String url_perpetual = "/cgi-bin/material/add_material";
	/** 临时素材上传地址 */
	public static final String url_temporary = "/cgi-bin/media/upload";
	/** 图文消息素材上传地址 */
	public static final String url_meida = "/cgi-bin/media/uploadimg";

	/**
	 * 获取临时文件的地址
	 * @param media_id
	 * @return
	 */
	public static File downImageByMedia(String media_id) {
		String url = WechatUtil.url + "/cgi-bin/media/get?access_token=" + WechatUtil.getAccess_token() + "&media_id=" + media_id;
		File file = WechatMediaUtil.downloadFileByGet(url);
		return file;
	}

	/**
	 * 上传媒体消息 
	 * @param type 上传文件类型 图片image
	 * @param file 上传的文件
	 * @param urls WechatMediaUtil下面的三个静态地址
	 * 
	 * @return 返回媒体标识
	 */
	public static String UploadMedia(String type, File file, String urls) {
		String media_id = "";
		if (StringUtils.isEmpty(type) || null == file) { //|| !file.exists()
			return null;
		}
		//标识，不重复(构造一个类似于form提交的状态)
		// 设置边界  
		String BOUNDARY = "----------" + System.currentTimeMillis();

		Map<String, String> con_map = new HashMap<>();
		// 设置请求头信息  
		con_map.put("Connection", "Keep-Alive");
		con_map.put("Charset", "UTF-8");
		con_map.put("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

		// 第一部分：  
		StringBuilder sb = new StringBuilder();
		sb.append("--"); // 必须多两道线  
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length() + "\";filename=\"" + file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");

		//脚部标识
		String foots = "\r\n--" + BOUNDARY + "--\r\n";
		String str = HttpUtil.sendPost(WechatUtil.url + urls + "?access_token=" + WechatUtil.getAccess_token() + "&type=" + type, sb.toString(), foots, con_map, file);

		JSONObject jsonObject = JSONObject.fromObject(str);

		//图文消息单独处理
		if (urls.equals(WechatMediaUtil.url_meida)) {
			String url = (String) jsonObject.get("url");
			return url;
		}

		media_id = (String) jsonObject.get("media_id");
		if (StringUtils.isNotEmpty(media_id)) {
			logger.info("上传微信媒体文件成功:" + str);
			return media_id;
		} else {
			logger.info("上传微信媒体文件失败:" + str);
		}

		return str;
	}

	/**
	 * 删除一个永久性素材
	 * @param media_id
	 * @return
	 */
	public static boolean delete_media(String media_id) {
		if (StringUtils.isEmpty(media_id)) {
			return false;
		}
		JSONObject jp = new JSONObject();
		jp.accumulate("media_id", media_id);

		String str = HttpUtil.sendPost(WechatUtil.url + "/cgi-bin/material/del_material?access_token=" + WechatUtil.getAccess_token(), jp.toString());
		JSONObject json = JSONObject.fromObject(str);
		//如果删除成功
		if ("0".equals(json.getString("errcode"))) {
			System.out.println(DateUtils.getNowTime_6() + "删除了一个id为：" + media_id + "的素材");
			return true;
		} else {
			System.out.println(DateUtils.getNowTime_6() + "删除id为：" + media_id + "的素材删除失败→" + str);
		}
		return false;
	}

	/** 删除全部的素材 */
	public static void delete_all_media(WechatMessageTypeEnum type) {
		if (null == type) {
			return;
		}
		//查找所有的素材
		JSONObject jp = new JSONObject();
		jp.accumulate("type", type.toString());
		jp.accumulate("offset", "0");
		jp.accumulate("count", "20");

		String str = HttpUtil.sendPost(WechatUtil.url + "/cgi-bin/material/batchget_material?access_token=" + WechatUtil.getAccess_token(), jp.toString());
		JSONObject json = JSONObject.fromObject(str);
		System.out.println(str);
		try {
			//素材总数
			Integer total_count = json.getInt("total_count");
			//如果是有素菜
			if (null != total_count) {
				if (total_count > 0) {
					JSONArray jsonArray = json.getJSONArray("item");
					for (Object obj : jsonArray) {
						JSONObject js1 = JSONObject.fromObject(obj);
						String media_id = js1.getString("media_id");
						//开始删除
						if (StringUtils.isNotEmpty(media_id)) {
							WechatMediaUtil.delete_media(media_id);
						}
					}
				}
				//没有删除完，再继续删除
				if (total_count >= 20) {
					WechatMediaUtil.delete_all_media(type);
				}

			} else {
				System.out.println("并无素材");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("删除出错");
		}
	}

	/**
	 * 组装xml对象
	 * @param bean
	 * @return
	 */
	public static String toMessageByXml(WeChatMessageBean bean) {

		StringBuffer sxml = new StringBuffer();
		sxml.append("<xml>");
		sxml.append("<ToUserName><![CDATA[" + bean.getToUserName() + "]]></ToUserName>");
		sxml.append("<FromUserName><![CDATA[" + bean.getFromUserName() + "]]></FromUserName>");
		sxml.append("<CreateTime>" + bean.getCreateTime() + "</CreateTime>");

		sxml.append("<MsgType><![CDATA[image]]></MsgType>");
		if (WechatMessageTypeEnum.image.equals(bean.getMsgType())) {
			sxml.append("<Image>");
			sxml.append("<MediaId><![CDATA[" + bean.getMediaId() + "]]></MediaId>");
			sxml.append("</Image>");
		}
		sxml.append("</xml>");

		return sxml.toString();
	}

	/**
	 * 微信多媒体文件下载
	 * @param urlPath
	 * @return
	 */
	public static File downloadFileByGet(String urlPath) {
		File file = null;
		try {

			URL u = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			String content_disposition = conn.getHeaderField("content-disposition");
			if (StringUtils.isEmpty(content_disposition)) {
				return file;
			}
			//微信服务器生成的文件名称
			String file_name = "";
			String[] content_arr = content_disposition.split(";");
			if (content_arr.length == 2) {
				String tmp = content_arr[1];
				int index = tmp.indexOf("\"");
				file_name = tmp.substring(index + 1, tmp.length() - 1);
			}
			//生成不同文件名称
			file = new File(file_name);
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
			byte[] buf = new byte[2048];
			int length = bis.read(buf);
			while (length != -1) {
				bos.write(buf, 0, length);
				length = bis.read(buf);
			}
			bos.close();
			bis.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	/**
	 * 添加永久性素材
	 * @param list 图文列表
	 * @return
	 */
	public static String add_news(List<TWechatMediaNews> list) {
		String media_id = "";
		if (CollectionUtils.isEmptyCollection(list)) {
			return media_id;
		}

		JSONObject jp = new JSONObject();

		JSONArray jr = new JSONArray();
		for (TWechatMediaNews tw : list) {
			JSONObject ja = new JSONObject();
			ja.accumulate("title", tw.getTitle());
			ja.accumulate("thumb_media_id", tw.getThumb_id());
			ja.accumulate("author", tw.getAuthor());
			ja.accumulate("digest", tw.getDigest());
			ja.accumulate("show_cover_pic", tw.getShow_cover_pic() ? "1" : "0");
			ja.accumulate("content", tw.getContent());
			ja.accumulate("content_source_url", tw.getContent_source_url());

			jr.add(ja);
		}

		jp.accumulate("articles", jr);

		String str = HttpUtil.sendPost(WechatUtil.url + "/cgi-bin/material/add_news?access_token=" + WechatUtil.getAccess_token(), jp.toString());
		JSONObject json = JSONObject.fromObject(str);
		System.out.println(str);
		//素材
		media_id = (String) json.get("media_id");
		return media_id;
	}

	public static void main(String[] args) {
		String token = "H3zj-yzG7bnMylGNRZ0E4BqYNj3g5ufNlTvezEx0fbi6V1gumrCMHby3d2lWU4VWnQRtmplLCblwxUkZK0hCaIcMr_EjC3anUDLPLTDGs910r8TfvHEBT_Apf0ObzOH3OVMeAGACJA";

		//查找所有的素材
		JSONObject jp = new JSONObject();
		jp.accumulate("type", "news");
		jp.accumulate("offset", "0");
		jp.accumulate("count", "20");

		String str = HttpUtil.sendPost(WechatUtil.url + "/cgi-bin/material/batchget_material?access_token=" + token, jp.toString());

		System.out.println(str);
	}

}
